﻿using Avalonia.Controls;
using Avalonia.Extensions.Controls;
using Avalonia.Threading;
using Bilibili.Common;
using Bilibili.Common.Log;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace Avalonia.BiliBili
{
    public abstract class WindowBase : AeroWindow
    {
        private object data;
        public object Data
        {
            get => data;
            set
            {
                data = value;
                Callback();
            }
        }
        public WindowBase() : base()
        {
            if (Debugger.IsAttached)
                this.AttachDevTools();
            Loaded += (sender, e) => AfterInitializeComponent();
        }
        protected abstract void AfterInitializeComponent();
        protected override void OnInitialized()
        {
            var fileName = Path.Combine(Extension.GetRoot(false), "Assets", "notification_icon.ico");
            Icon = new WindowIcon(fileName);
            MinWidth = 640;
            MinHeight = 480;
            InitializeWindow();
        }
        public virtual void InitializeWindow() { }
        public virtual void Callback() { }
        protected void RunOnUiThread(Action action)
        {
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                try
                {
                    action?.Invoke();
                }
                catch (Exception ex)
                {
                    LogManager.Instance.LogError("RunOnUiThread", ex);
                }
            }, DispatcherPriority.Loaded);
        }
        protected void RunOnUiThread(Func<Task> action)
        {
            Dispatcher.UIThread.InvokeAsync(async () =>
            {
                try
                {
                    await action?.Invoke();
                }
                catch (Exception ex)
                {
                    LogManager.Instance.LogError("RunOnUiThread", ex);
                }
            }, DispatcherPriority.Loaded);
        }
    }
}